package timer;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.LongAdder;

/**
 * @author ZhuQi
 * @ClassName Demo
 * @Date 2022/11/8 15:27
 * @Version 1.0
 * @Description 测试 Timer
 */
public class Demo {

    /**
     * 测试 Timer 实现定时任务
     * @param args
     */
    public static void main(String[] args) {
        Timer timer = new Timer("test thread", false);
        worker worker = new worker(timer);
        timer.schedule(worker, 1000L,1000L);
    }
}
class worker extends TimerTask{

    private Timer timer;

    private LongAdder longAdder = new LongAdder();

    public worker() {
    }

    public worker(Timer timer) {
        this.timer = timer;
    }

    @Override
    public long scheduledExecutionTime() {
        return super.scheduledExecutionTime();
    }

    @Override
    public boolean cancel() {
        System.out.println("取消");
        return super.cancel();
    }

    @Override
    public void run() {
        System.out.println("工作中");
        longAdder.increment();
        long sum = longAdder.sum();
        if (sum == 10) {
            timer.cancel();
        }
    }
}